import sys
import time

from PyQt5 import QtWidgets
from PyQt5.QtCore import QRunnable, QThread, pyqtSignal, QObject, QThreadPool
from PyQt5.QtWidgets import QDialog

from test.ui_mainwindow import Ui_MainWindow
from test.ui_dialog_test import Ui_Dialog


class DialogWindow(QDialog, Ui_Dialog):
    stop_thread = pyqtSignal()  # 定义关闭子线程的信号

    def __init__(self, parent=None):
        super(DialogWindow, self).__init__(parent)
        self.setupUi(self)

    def update_progressbar(self, p_int):
        self.progressBar.setValue(p_int)

    def closeEvent(self, event):
        self.stop_thread.emit()
        pass


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.count = 0
        self.pool = QThreadPool()
        self.pool.globalInstance()
        self.pool.setMaxThreadCount(10)  # 设置最大线程数

    def open_dialog(self):
        dialog = DialogWindow(self)
        dialog.show()
        thread = RunThread(self.count)
        self.count += 1
        thread.signal.update_pb.connect(dialog.update_progressbar)
        # dialog.stop_thread.connect(thread.stop)
        # self.thread.start()
        self.pool.start(thread)  # 线程池分配一个线程运行该任务


class Signal1(QObject):
    update_pb = pyqtSignal(int)


class RunThread(QRunnable):
    """使用QThreadPool, 线程需要继承QRunnable,而QRunnable只是namespace,没有继承QT的信号机制
    所以需要另外继承QObject来使用信号,这里就直接使用外部封装的信号"""

    def __init__(self, count):
        super().__init__()
        self.count = count
        self.signal = Signal1()  # 信号

    def run(self):
        for i in range(1, 101):
            print('thread_%s' % self.count, i, QThread().currentThreadId())
            self.signal.update_pb.emit(i)
            time.sleep(1)
        pass

    def stop_thread(self):
        self.autoDelete()


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())

